/**
 * 导航路由相关state
 */
import { atom } from "recoil";
import { RouteVO } from "../service/rbac/menu-service";

export const defaultOpenKeys = ["9"];
export const defaultSelectedKeys = ["4"];
export const defaultOpenStatus = false;
export const defaultTabHsitory = [];
export const defaultActiveTab = 0;

export type naviType = {
  defaultOpenKeys: string[];
  defaultSelectedKeys: string[];
  defaultOpenStatus: boolean;
  tabHistory: { title: string; path: string; key: string[] }[];
  tabActiveIndex: number;
};
export let initialState: naviType = {
  /**
   * side 选中的的 key
   */
  defaultOpenKeys: defaultOpenKeys,

  /**
   * side 打开的 key
   */
  defaultSelectedKeys: defaultSelectedKeys,

  /**
   * 是否展开侧边栏
   */
  defaultOpenStatus: defaultOpenStatus,
  tabHistory: defaultTabHsitory,
  tabActiveIndex: defaultActiveTab,
};

const naviStr = sessionStorage.getItem("__BEEFSOLVE_BACKWEB__NAVI__");
if (naviStr) {
  initialState = { ...JSON.parse(naviStr) };
}

/**
 * 获取到全部的父路由
 * @param parentId 父路由ID
 * @param routes  路由列表
 * @param parentIds 容器
 * @returns
 */
export const getNaviParentId = (
  parentId: number,
  routes: RouteVO[],
  parentIds: string[]
): string[] => {
  if (parentId === 0) {
    return parentIds;
  }
  routes.forEach((e) => {
    if (e.id === parentId) {
      parentIds.push(parentId + "");
      getNaviParentId(e.parentId, routes, parentIds);
    }
  });
  return parentIds;
};

/**
 * 获取到全部的父路由不包含自己
 * @param parentId 父路由ID
 * @param routes  路由列表
 * @param parentIds 容器
 * @returns
 */
export const getNaviParentIds = (
  parentId: number,
  routes: RouteVO[],
  parentIds: string[]
): string[] => {
  if (parentId === 0) {
    return parentIds;
  }
  routes.forEach((e) => {
    if (e.id === parentId) {
      getNaviParentId(e.parentId, routes, parentIds);
    }
  });
  return parentIds;
};

/**
 * 获取到路由面包屑
 * @param id 路由ID
 * @param routes  路由列表
 * @param breadcrumbContainer  容器
 * @returns
 */

export const getBreadcrumb = (
  id: number,
  routes: RouteVO[],
  breadcrumbContainer: { title: string }[]
): { title: string }[] => {
  if (id === 0) {
    breadcrumbContainer.unshift({ title: "首页" });
    return breadcrumbContainer;
  }
  routes.forEach((e) => {
    if (e.id === id) {
      breadcrumbContainer.unshift({ title: e.meta.title });
      getBreadcrumb(e.parentId, routes, breadcrumbContainer);
    }
  });
  return breadcrumbContainer;
};

export const naviState = atom({
  key: "naviState",
  default: initialState,
});
